
var layer = layui.layer //弹层
    , table = layui.table //表格
    , form = layui.form,
    $ = layui.jquery,
    laydate = layui.laydate,
    isFinance,
    colorpicker = layui.colorpicker,
    billNo = getQueryVariable("billNo"),
    contractNo=getQueryVariable("contractNo")
;
//判断当前用户是否为管理员 角色 true:是 false 否
let isAdmin = false;
//判断当前登录用户是否为 营销部门的总监
is_marketing_director();

//判断当前用户是否为管理员 角色 true:是 false 否
getIsAdmin();

//工厂财务标签 有该标签:false 无该标签:true
let isFactoryFinance = true;
isFactoryFinance = getAllRolesByCurr("GCCWYF001");

function getAllJson(jsons, type) {
    let tmpitem = []
    for (let item of jsons) {
        let tmparr = {}
        if (2 == type) {
            tmparr["value"] = item["name"];
            tmparr["name"] = item["name"];
        }else {
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
        }

        if (item["users"]) {
            for (let it of item["users"]) {
                item["list"].push(it)
            }
        }
        if (item["list"] && item["list"].length) {
            tmparr["children"] = this.getAllJson(item["list"], type);
            tmpitem.push(tmparr)
        } else {
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,

        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


let operationList=[];
let salesmanList=[];
let deptOperationList=[];
let deptSalesmanList=[];

(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let data1 = treeList.list;
        let data2 = JSON.parse(JSON.stringify(treeList)).list;
        let userTree = getAllJson(data1, 1);
        operationList=getxmselect("#operationNo","operationNo", userTree);
        let salesmanTree = getAllJson(data2, 2);
        salesmanList = getxmselect("#salesmanCode","salesmanCode", salesmanTree);
    }else {
        operationList=getxmselect("#operationNo","operationNo", [{name: user.name, value: user.code}]);
        salesmanList =getxmselect("#salesmanCode","salesmanCode", [{name: user.name, value: user.code}]);
    }

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

})()

lay('.starttime').each(function () {
    laydate.render({
        elem: this
    });
});

let isMarketingDirector = false;

//判断当前登录用户是否为 营销部门的总监 角色 true:是 false 否
function is_marketing_director() {
    $.ajax({
        url: 'customer/isMarketingDirector',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isMarketingDirector = da.data;
            }
        }
    });
}


function getIsAdmin() {
    $.ajax({
        url: 'customer/isAdmin',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isAdmin = da.data;
            }
        }
    });
}

//判断当前登录用户是否为 财务
checkIsFinance();

//判断当前登录用户是否为 财务
function checkIsFinance(){
    $.ajax({
        url: 'cost/isFinance',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isFinance = date.data
        }
    })
}

let isMsn = "否";
//判断当前登录用户是否为 管理员
checkIsMsn();

//判断当前登录用户是否为 管理员
function checkIsMsn() {
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn = date.data
        }
    })
}


layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;

    let optionData = [
        {
            txt:"收款金额明细统计",
            event: "s1"
        },
        {
            txt:"按发票应收款统计",
            event: "s2"
        },
        {
            txt:"按发票应收统计价格术语不同",
            event: "s2diff"
        },
        {
            txt:"业务员年度认领金额统计",
            event: "s3"
        },
        {
            txt:"按合同应收款统计",
            event: "s4"
        }
    ]

    let flag = isMarketingDirector || isFinance === "是" || isAdmin;

    if(flag){
        //是总监、财务、管理员,开放额外菜单
        let newOptionData = [
            {
                txt:"FQ利润统计表",
                event: "FQStatistics"
            },
            {
                txt:"产品统计",
                event: "productStatistics"
            },
            {
                txt:"产品出货详情",
                event: "s6"
            }
        ]
        optionData.push.apply(optionData, newOptionData);
    }

    //管理员、财务
    let flagOrderDetail =  isFinance === "是" || isAdmin;
    if(flagOrderDetail){
        //是财务、管理员,开放额外菜单
        let newOrderDetailOptionData = [
            {
                txt:"订单详情",
                event: "orderDetail"
            }
        ]
        optionData.push.apply(optionData, newOrderDetailOptionData);
    }

    dropdown.suite("#collectionBtn", {
        showBy:"hover",
        align:"left",
        menus: optionData
    });

    dropdown.onFilter("collectionStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/Money/tpl/collectionStatistics1.jsp","收款金额明细统计")
                break
            case "s2":
                parent.intab("views/jsp/Money/tpl/collectionStatistics2.jsp","按发票应收款统计")
                break
            case "s2diff":
                parent.intab("views/jsp/Money/tpl/collectionStatistics2diff.jsp","按发票应收统计价格术语不同")
                break
            case "s3":
                parent.intab("views/jsp/Money/tpl/collectionStatistics3.jsp","业务员年度认领金额统计")
                break
            case "s4":
                parent.intab("views/jsp/Money/tpl/collectionStatistics4.jsp","按合同应收款统计")
                break
            case "FQStatistics":
                parent.intab("views/jsp/Money/tpl/collectionStatisticsForFQ.jsp","FQ利润统计表")
                break
            case "productStatistics":
                parent.intab("views/jsp/Money/tpl/productStatistics.jsp","产品统计")
                break
            case "s6":
                parent.intab("views/jsp/Money/tpl/collectionStatistics6.jsp","产品出货详情")
                break
            case "orderDetail":
                parent.intab("views/jsp/Money/tpl/orderDetailStatistics.jsp","订单详情")
                break
        }
    });
})

layer.ready(function () {
    //获取币种
    $.ajax({
        url: "receivePayment/getCurrencyInfo",
        success: function (data) {
            if (data.status == 200) {
                for (let i in data.data) {
                    $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });

    //获取所有公司信息
    $.ajax({
        url:"receivePayment/getCompanyInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    //公司名称
                    $('#voucherCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });

    $.ajax({
        url: "otherOutStock/getAllUserInfo",
        success: function (data) {
            if (data.status == 200) {
                for (let i in data.data) {
                    $('.user').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });

    let searchURL = window.location.search;
    searchURL = searchURL.substring(1, searchURL.length);
    let type = searchURL.split("&")[0].split("=")[1];
    let obj = {operationNo : user.code, salesmanCode : user.code}
    if(!isEmpty(type) && type == "statistics"){
        //来源于控制台统计

        //获取当月开始日期
        let time = new Date();
        let month = ("0" + (time.getMonth() + 1)).slice(-2);
        let year = time.getFullYear();
        //获取当月第一天
        let startDay = new Date(year, month, 1);
        let startCurryDay = startDay.getDate();
        startCurryDay = startCurryDay < 10 ? '0' + startCurryDay : startCurryDay;
        let startDate = time.getFullYear() + "-" + (month) + "-" + (startCurryDay);
        //签约日期
        laydate.render({
            elem: '#startTime',
            value: startDate,
            isInitValue: true
        });

        //获取当月结束日期
        let endDay = new Date(year, month, 0);
        let endCurryDay = endDay.getDate();
        endCurryDay = endCurryDay < 10 ? '0' + endCurryDay : endCurryDay;
        let endDate = time.getFullYear() + "-" + (month) + "-" + (endCurryDay);
        //签约日期
        laydate.render({
            elem: '#endTime',
            value: endDate,
            isInitValue: true
        });

        obj = {operationNo : user.code, startTime : startDate, endTime : endDate, status : 2}
    }
    if(!isEmpty(billNo)){
        //来源于收款统计(按发票应收款统计)
        $.ajax({
            url: "receivePayment/statistics/getReceivePaymentId?billNo="+billNo,
            async:false,
            success: function (data) {
                if (data.status == 200) {
                    obj = {ids : data.data}
                }
            }
        });
    }

    if (!isEmpty(contractNo)){
        $("#info").val(contractNo)
        let ids=[];
        $.ajax({
            url:'receivePayment/getReceivePaymentByContractNo?contractNo='+contractNo,
            type: 'GET',
            async: false, // 同步
            success: function (data) {
                let da=data.data;
                if (da.length>0){
                    for (let i in da){
                        ids.push(da[i].parentId)
                    }
                }
            }
        })

        obj={ids:ids.join(",")}
    }
    initTable(obj);
});

form.render();//表单刷新
function initTable(obj){
    table.render({
        elem: '#maininformation'
        ,where:obj
        , url: 'receivePayment/getReceivePaymentListByPage'
        , toolbar: '#maininformationtoolbar'
        ,totalRow: true
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            , {field: 'statusStr', title: '单据类型', sort: true, width: 120}
            , {field: 'billNo', title: '收款编码', sort: true, width: 200, event: "receiptnumber"}
            , {field: 'time', title: '收款日期', sort: true, width: 120}
            , {field: 'customerName', title: '客户名称', sort: true, width: 120}
            , {field: 'currency', title: '币种', sort: true, width: 120}
            , {field: 'collectionAmount', title: '收汇金额', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'entryAmount', title: '入账金额', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'claimed', title: '已认领', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'toBeClaimed', title: '待认领', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'bankDeductionExcept', title: '银行扣费（外）', sort: true, width: 140, totalRow: true, align: 'right'}
            , {field: 'claimSalesman', title: '认领业务员', sort: true, width: 180}
            , {field: 'claimCustomer', title: '认领客户', sort: true, width: 180}
            , {field: 'bankDeductionCapital', title: '银行扣费（本）', sort: true, width: 140, totalRow: true, align: 'right'}
            , {field: 'accountNo', title: '收款账号', sort: true, width: 120}
            , {field: 'voucherCompanyName', title: '制单公司', sort: true, width: 120}
            , {field: 'rmbRate', title: '人民币汇率', sort: true, width: 120, align: 'right'}
            , {field: 'usdRate', title: '美金汇率', sort: true, width: 120, align: 'right'}
            , {field: 'splitCompletedAmount', title: '已拆分金额', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'undividedAmount', title: '未拆分金额', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'contractUnclaimedAmount', title: '合同未认领金额', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'refundAmount', title: '退款金额', sort: true, width: 120, totalRow: true, align: 'right'}
            , {field: 'operator', title: '操作员', sort: true, width: 120}
            , {field: 'memo', title: '备注', sort: true, width: 200}
            , {field: 'salesman', title: '登记业务员', sort: true, width: 120}
            , {fixed: 'right', width: 325, toolbar: '#maininformationeditor', title: '操作'}
        ]]
        , id: 'maininformationtableid'
        , height: $(document).height() - $('#maininformation').offset().top - 75
        , page: true
        , limit: 100
        , limits: [100, 200, 300, 600, 900]
        , done(res, curr, count) {
            lay('.colorvalue').each(function () {
                let xb = $(this).attr("data-id");
                let colors = "";
                for (var i = 0; i < res.data.length; i++) {
                    if (res.data[i].id == xb && typeof (res.data[i].markColor) != "undefined" && res.data[i].markColor != "") {
                        Layui_SetDataTableRowColor('tablediv', $(this).attr("data-index"), res.data[i].markColor);
                        colors = res.data[i].markColor;
                    }
                }
                colorpicker.render({
                    elem: this //绑定元素
                    , color: colors //设置默认色
                    , done: function (color) {//点击颜色选择器的“确认”和“清除”按钮，均会触发 done 回调，回调返回当前选择的色值
                        let index = $(this.elem).attr("data-index");
                        Layui_SetDataTableRowColor('tablediv', index, color);
                        //保存修改的颜色
                        let id = res.data[index].id;
                        let req = {
                            id: id,
                            color: color
                        }
                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            contentType: 'application/json',
                            data: JSON.stringify(req),
                            url: "receivePayment/updateMarkColor",
                            success: function (data) {
                                if (data.status == 200) {
                                    layer.msg('修改成功');
                                } else {
                                    layer.msg(data.msg);
                                }
                            }
                        });
                    }

                });
            });
        }
    });
}

//设置layui datatable的某一行的颜色
//DivId:datatable父div的 id;RowIndex:行序列号；Color：颜色字符串，如'#FF3030'
function Layui_SetDataTableRowColor(DivId, RowIndex, Color) {
    try {
        var div = document.getElementById(DivId);
        if (div != null) //找到对象了
        {
            var table_main = div.getElementsByClassName('layui-table-main');   //通过class获取table_main
            if (table_main != null && table_main.length > 0) {
                var table = table_main[0].getElementsByClassName('layui-table');   //通过class获取table
                if (table != null && table.length > 0) {
                    var trs = table[0].querySelectorAll("tr");
                    if (trs != null && trs.length > 0) {
                        trs[RowIndex].style.backgroundColor = Color;//背景颜色
                    }
                }
            }

        }
    } catch (e) {
        console.log(e.message);
    }
}

table.on('tool(maininformationtable)', function (obj) {
    let data = obj.data;
    let id = data.id;
    let status = data.status;
    if (obj.event === 'update') {
        parent.intab("views/jsp/Money/tpl/receivePaymentUpdate.jsp?id=" + obj.data.id, "修改收款")
    } else if (obj.event === 'delect') {
        layer.confirm("确认删除？",
            confirmInfo(3, 6),
            function (index) {
                layer.close(index);
                let dataBases = {
                    id: id,
                    status: status
                }
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: 'application/json',
                    data: JSON.stringify(dataBases),
                    url: "receivePayment/delete",
                    success: function (res) {
                        if (res.status == 200) {
                            layer.msg("删除成功", {icon: 6});
                            table.reload('maininformationtableid', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                                , where: data.field
                            }, 'data');
                            return false;
                        } else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    }
                });
            });
    } else if (obj.event === 'collectioncase') {
        layer.confirm('确定收款招领吗?', confirmInfo(3, 5), function (index) {
            operationData(id, 1, "收款招领");
        });
    } else if (obj.event === 'andreturn') {
        layer.confirm('确定招领退回吗?', confirmInfo(3, 5), function (index) {
            operationData(id, 2, "招领退回");
        });
    } else if (obj.event === 'paymentclaim') {
        //收款认领
        layer.open({
            type: 2,
            area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
            content: 'views/jsp/Money/tpl/paymentclaim.jsp?id=' + id
        });
    } else if (obj.event === 'claimtoconfirm') {
        //认领确认
        layer.open({
            type: 2,
            area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
            content: 'views/jsp/Money/tpl/claimtoconfirm.jsp?id=' + id
        });
    } else if (obj.event === 'backFind') {
        //退回招领
        layer.confirm('确认退回招领吗?', confirmInfo(3, 5), function (index) {
            operationData(id, 3, "确认退回招领");
        });
    } else if (obj.event === 'confirmback') {
        layer.confirm('确认退回吗?', confirmInfo(3, 5), function (index) {
            operationData(id, 3, "确认退回");
        });
    } else if (obj.event === 'gatheringsplit') {
        //收款拆分
        layer.open({
            type: 2,
            area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
            content: 'views/jsp/Money/tpl/akeybreakup.jsp?id=' + id
        });
    } else if (obj.event === 'split') {
        layer.confirm('确定拆分完成吗?', confirmInfo(3, 5), function (index) {
            operationData(id, 4, "拆分完成");
        });
    } else if (obj.event === 'completethereturn') {
        layer.confirm('确定完成退回吗?', confirmInfo(3, 5), function (index) {
            operationData(id, 5, "完成退回");
        });
    } else if (obj.event === 'reduction') {
        layer.confirm('确定还原吗?', confirmInfo(3, 5), function (index) {
            operationData(id, 6, "还原");
        });
    } else if (obj.event === "receiptnumber") {
        parent.intab("views/jsp/Money/tpl/viewcollection.jsp?id=" + id, "收款明细")
    }
});


function operationData(id, operation, msg) {
    let data = {
        id: id,
        operation: operation
    }
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify(data),
        url: "receivePayment/operation",
        success: function (res) {
            if (res.status == 200) {
                layer.msg(msg, {icon: 6});
                table.reload('maininformationtableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: data.field
                }, 'data');
                return false;
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

form.on('submit(submitform)', function (data) {
    if (deptSalesmanList.getValue('nameStr')!=""){
        data.field.deptSalesmanCode=deptSalesmanList.getValue('nameStr');//获取name字符串
    }
    initTable(data.field);
    return false;
});

table.on('toolbar(maininformationtable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'news':
            parent.intab("views/jsp/Money/tpl/newupcollection.jsp", "新增收款");
            break;
        case 'dels':
            let data = checkStatus.data, delList = [];
            let flag = false;
            data.forEach(function (n, i) {
                if(n.status == 2){
                    flag = true;
                }
                delList.push(n.id);
            });
            if (delList != '') {
                let msg = "";
                if(flag){
                    msg = "存在招领箱数据，该数据将不会被删除，是否继续删除？";
                }else {
                    msg = "确定删除所选项吗？";
                }
                layer.confirm(msg, confirmInfo(3, 5), function (index) {
                    var cbList = table.cache["maininformationtableid"];
                    for (var i = 0; i < cbList.length; i++) {
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("maininformationtableid", {
                        data: cbList,
                    });
                    let ids = "";
                    for (let i in delList) {
                        if (ids.length == 0) {
                            ids = ids + delList[i];
                        } else {
                            ids = ids + "," + delList[i];
                        }
                    }
                    $.ajax({
                        url: "receivePayment/batchDelete?ids=" + ids,
                        success: function (data) {
                            if (data.status == 200) {
                                layer.msg('删除成功');
                            } else {
                                layer.msg(data.msg);
                            }
                        }
                    });

                })
            } else {
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

function getIdByCheckStatus(checkStatus) {
    let id = "";
    if (checkStatus.length != 0) {
        for (let i = 0; i < checkStatus.length; i++) {
            if (i == checkStatus.length - 1) {
                id += checkStatus[i].id;
            } else {
                id += checkStatus[i].id + ",";
            }
        }
    }
    return id;
}

$("#refundregistration").on("click", function () {
    //获取选中的数据
    let checkStatus = table.checkStatus("maininformationtableid").data;
    if (checkStatus.length == 0) {
        layer.msg("请选择数据")
        return false;
    }
    let id = getIdByCheckStatus(checkStatus);
    layer.open({
        type: 2,
        area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
        content: 'views/jsp/Money/tpl/refundregistration.jsp?id=' + id
    });
});
$("#akeybreakup").on("click", function () {
    //获取选中的数据
    let checkStatus = table.checkStatus("maininformationtableid").data;
    if (checkStatus.length == 0) {
        layer.msg("请选择数据")
        return false;
    }
    let id = getIdByCheckStatus(checkStatus);
    layer.open({
        type: 2,
        area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
        content: 'views/jsp/Money/tpl/akeybreakup.jsp?id=' + id
    });
});
$("#statistical").on("click", function () {
    parent.intab("views/jsp/Money/tpl/statistics.jsp", "收款统计")
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

$("#clear").on("click",function () {
    operationList.setValue([ ]);
    salesmanList.setValue([ ]);
    deptOperationList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
});